package com.weilx959.spt.app.context;

import com.weilx959.spt.app.listener.LogTailerListener;
import com.weilx959.spt.core.constants.CommonConstants;
import org.apache.commons.io.input.Tailer;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Objects;
import java.util.function.Consumer;

public class LogThreadContext {
    private static Tailer tailer;

    private LogThreadContext() {
    }

    public static synchronized void start(Consumer<Exception> exceptionHandler, Consumer<String> logHandler) {
        if (Objects.nonNull(tailer)) {
            return;
        }
        tailer = Tailer.builder()
            .setFile(CommonConstants.LOG_FILE)
            .setTailerListener(new LogTailerListener(exceptionHandler, logHandler))
            .setDelayDuration(Duration.ofSeconds(1L))
            .setCharset(StandardCharsets.UTF_8)
            .setStartThread(true)
            .setTailFromEnd(true)
            .get();
    }

    public static synchronized void stop() {
        if (Objects.nonNull(tailer)) {
            tailer.close();
            tailer = null;
        }
    }
}
